package com.kyrioscraft.cloud.thead.jdklab.tools.reentrant;

import java.util.Random;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * @Author kyrioscraft
 * @Date 2019/2/18 14:09
 * @Description CountDownLatch 一个线程通过await阻塞等待其他线程countDown，countDown结束后执行阻塞的线程
 **/
public class CountDownLatchDemo implements Runnable {
    static final CountDownLatch end = new CountDownLatch(10);
    static final CountDownLatchDemo demo = new CountDownLatchDemo();
    @Override
    public void run() {
        try {
            Thread.sleep(new Random().nextInt(10)*1000);
            System.out.println("check complete");
            end.countDown();

            Thread.sleep(20000);
            System.out.println("countDown后面执行的");
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) throws InterruptedException{
        ExecutorService exec = Executors.newFixedThreadPool(10);
        for(int i=0; i< 10 ; i++) {
            exec.submit(demo);
        }
        new Thread(()->{
            try {
                end.await();
                System.out.println("Fire!");
            }catch (InterruptedException e){

            } finally {
                exec.shutdown();
            }

        }).start();

        System.out.println("main thread finish");

    }
}
